//
//  RWSubTagTableViewController.m
//  baisibudejie
//
//  Created by renwei on 16/9/19.
//  Copyright © 2016年 renwei. All rights reserved.
//

#import "RWSubTagTableViewController.h"

#import "RWSubTagItem.h"
#import "XMGSubTagCell.h"

#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import <SVProgressHUD.h>

static NSString * const ID = @"cell";

@interface RWSubTagTableViewController ()

@property (nonatomic, strong) NSArray    *subTags;

@property (nonatomic, strong) AFHTTPSessionManager *mgr;

@end

@implementation RWSubTagTableViewController

// 接口文档: 请求url(基本url+请求参数) 请求方式
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"推介标签";
    
    // 展示标签数据 -> 请求数据(接口文档) -> 解析数据(写成Plist)(image_list,sub_number,theme_name) -> 设计模型 -> 字典转模型 -> 展示数据
    // 加载数据
    [self loadData];
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"XMGSubTagCell" bundle:nil] forCellReuseIdentifier:ID];
    
    // 处理cell 的分割线， 1.自定义分割线， 2.系统属性, 3.万能方式（重写cell的setframe），需要了解tableView的底层实现［a.取消系统自带的分割线， b.把tableview的背景色设成分割线的背景色， c.重写serframe方法］
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = RWColor(220, 220, 220);
    
    //  提示用户当前正在加载数据
    [SVProgressHUD showWithStatus:@"正在加载中。。。。。。"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // 1.加载完成取消
    [SVProgressHUD dismiss];
    
    // 2.取消之前的请求
    [_mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
}

#pragma mark - 请求数据
- (void)loadData {

    // 1. 创建请求会话管理者
    self.mgr = [AFHTTPSessionManager manager];
    
    // 2. 拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"tag_recommend";
    parameters[@"action"] = @"sub";
    parameters[@"c"] = @"topic";
    
    // 3. 发送请求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [_mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 加载完成取消
            [SVProgressHUD dismiss];
            
            // 字典数组转化成模型数组
            self.subTags = [RWSubTagItem mj_objectArrayWithKeyValuesArray:responseObject];
            
            // 刷新数据
            [self.tableView reloadData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            RWLog(@"请求错误");
            // 加载完成取消
            [SVProgressHUD dismiss];
            
        }];
    });
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.subTags.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    // 自定义cell
    XMGSubTagCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

//    static NSString *cellid = @"cellid";
//    
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
//
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
//    }
    
    // 取出模型
    RWSubTagItem *item = self.subTags[indexPath.row];
    cell.item = item;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
